package com.zzp.basepresenter.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.zzp.basepresenter.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class ImageManagerUtil {
    private static ImageManagerUtil instance;

    private int normalConnors = 10;

    public static ImageManagerUtil getInstance() {
        if (instance == null) {
            synchronized (ImageManagerUtil.class) {
                if (instance == null) {
                    instance = new ImageManagerUtil();
                }
            }
        }
        return instance;
    }

    /*
     * 清理ImageView图片资源以及ImageView
     * */
    public void releaseImageViewResource(View imageView) {
        if (imageView == null) return;
        Drawable drawable = null;
        if (imageView instanceof ImageView) {
            drawable = ((ImageView) imageView).getDrawable();
        }
        if (imageView instanceof RelativeLayout) {
            drawable = imageView.getBackground();
        }
        if (imageView instanceof LinearLayout) {
            drawable = imageView.getBackground();
        }
        if (imageView instanceof FrameLayout) {
            drawable = imageView.getBackground();
        }
        if (imageView instanceof RadioButton) {
            drawable = imageView.getBackground();
        }
        if (drawable != null && drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            //将imageView从父容器移除，并将imag置为null
            if (imageView != null) {
                if (((ViewGroup) imageView.getParent()) != null) {
                    ((ViewGroup) imageView.getParent()).removeView(imageView);
                }
                imageView = null;
            }
        }
    }

    /**
     * 加载图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadThumbWithFailed(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        RequestOptions options = new RequestOptions();
        options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
        options.placeholder(R.drawable.shape_image_loading_5dp);
        Glide.with(context).applyDefaultRequestOptions(options).load(uri).into(imageView);
    }

    /**
     * 加载gif图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadGIF(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .asGif()
                .placeholder(R.drawable.shape_image_loading_5dp)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(imageView);
    }


    /**
     * 加载gif图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadGIFGray(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .asGif()
                .placeholder(R.drawable.style_t80_solid_layout)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(imageView);
    }


    /**
     * 加载gif图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadGIF5(Context context, String uri, final ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .asGif()
                .load(uri)
                .transform(new GlideRoundedCornersTransform(DensityUtil.dip2px(context, 5)
                        , GlideRoundedCornersTransform.CornerType.ALL))
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(imageView);
    }

    /**
     * 加载圆形图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadCircleImage(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .load(uri)
//                .apply(requestOptions)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .transform(new GlideRoundedCornersTransform(DensityUtil.dip2px(context, 100)
                        , GlideRoundedCornersTransform.CornerType.ALL))
                .into(imageView);
    }

    /**
     * 加载圆形图片
     *
     * @param res       地址
     * @param imageView 设置image
     */
    public void LoadCircleImage(Context context, int res, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .load(res)
//                .apply(requestOptions)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .transform(new GlideRoundedCornersTransform(DensityUtil.dip2px(context, 100)
                        , GlideRoundedCornersTransform.CornerType.ALL))
                .into(imageView);
    }


    /**
     * 加载圆形图片
     *
     * @param bitmap    bitmap
     * @param imageView 设置image
     */
    public void LoadCircleImage(Context context, Bitmap bitmap, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .load(bitmap)
//                .apply(requestOptions)
                .transform(new GlideRoundedCornersTransform(DensityUtil.dip2px(context, 100)
                        , GlideRoundedCornersTransform.CornerType.ALL))
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(imageView);
    }


    /**
     * 加载图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadImageWithTopCorner(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context).clear(imageView);
        Glide.with(context)
                .load(uri)
//                .apply(requestOptions)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .transform(new GlideRoundedCornersTransform(DensityUtil.dip2px(context, 10)
                        , GlideRoundedCornersTransform.CornerType.TOP_LEFT_TOP_RIGHT))
                .into(imageView);
    }

    /**
     * 加载图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadImageWithCorner5(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context)
                .load(uri)
//                .apply(requestOptions)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .placeholder(R.drawable.shape_image_loading_5dp)
                .transform(new GlideRoundedCornersTransform(DensityUtil.dip2px(context, 5)
                        , GlideRoundedCornersTransform.CornerType.ALL))
                .into(imageView);
    }

    /**
     * 加载图片
     *
     * @param uri       地址
     * @param imageView 设置image
     */
    public void LoadImage(Context context, String uri, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context)
                .load(uri)
                .placeholder(R.drawable.style_t80_solid_layout)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(imageView);
    }

    /**
     * 加载图片
     *
     * @param res       地址
     * @param imageView 设置image
     */
    public void LoadImage(Context context, int res, ImageView imageView) {
        if (context == null || imageView == null) {
            return;
        }
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }
        Glide.with(context)
                .load(res)
                .placeholder(R.drawable.style_t80_solid_layout)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(imageView);
    }

    /**
     * 高斯模糊图片
     */
    public void loadMultiTransformation(final Context context, String uri, ImageView imageView) {
        // 圆角和高斯模糊
        MultiTransformation multi = new MultiTransformation<Bitmap>(
                new BlurTransformation(0, 3),
                new GlideRoundedCornersTransform(0, GlideRoundedCornersTransform.CornerType.ALL));

        Glide.with(context)
                .load(uri)
                .apply(new RequestOptions().transform(multi))
                .into(imageView);
    }

    /**
     * 高斯模糊图片
     */
    public void loadMultiTransformation(final Context context, String uri, final View view) {
        // 圆角和高斯模糊
        MultiTransformation multi = new MultiTransformation<Bitmap>(
                new GlideRoundedCornersTransform(13, GlideRoundedCornersTransform.CornerType.ALL)
                , new BlurTransformation(20, 1));
        Glide.with(context)
                .asDrawable()
                .load(uri)
                .centerCrop()
//                .apply(new RequestOptions().transform(multi))
                .transform(multi)
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        view.setBackground(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    public Drawable getGSbitmap(Context context, Bitmap bitmap) {
//        Drawable oldbg = view.getBackground();//获得背景图片
        // 将Drawable,转成Bitmap
//        Bitmap bitmap = ((BitmapDrawable) oldbg).getBitmap();
        Bitmap finalBitmap = EasyBlur.with(context)
                .bitmap(bitmap) //要模糊的图片
                .radius(5)//模糊半径
                .scale(2)//指定模糊前缩小的倍数
                .policy(EasyBlur.BlurPolicy.FAST_BLUR)//使用fastBlur
                .blur();
        return new BitmapDrawable(finalBitmap);
    }


    public void savePic(final Context context, String url) {
        try {
            if (!Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                ToastUtils.getInstance().ShortToast(context, R.string.no_sdcard);
                return;
            }
            if (TextUtils.isEmpty(url)) {
                return;
            }
            File downFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DCIM),
                    url.substring(url.lastIndexOf("/"), url.length()));
            if (!downFile.exists()) {
                downFile.getParentFile().mkdirs();
                downFile.createNewFile();
            }
            if (!downFile.exists()) {
                ToastUtils.getInstance().ShortToast(context, "文件写入失败");
            }
            RequestParams params = new RequestParams(url);
            params.setAutoRename(false);
            params.setSaveFilePath(downFile.getAbsolutePath());
            x.http().get(params, new Callback.ProgressCallback<File>() {
                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {

                }

                @Override
                public void onLoading(long l, long l1, boolean b) {
                }

                @Override
                public void onSuccess(File file) {
                    if (file.exists()) {
                        // 其次把文件插入到系统图库
                        try {
                            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                    file.getAbsolutePath(), file.getName(), null);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        MediaUtils.updateToMedia(context, file.getAbsolutePath());
                        ToastUtils.getInstance().ShortToast(context, "图片保存成功");
                    } else {
                        ToastUtils.getInstance().ShortToast(context, "图片保存失败");
                    }
                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onFinished() {
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存bitmap到本地
     *
     * @return
     */
    public File saveBitmap2File(Context context, Bitmap bitmap) {
        File filePic = null;
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            ToastUtils.getInstance().ShortToast(context, R.string.no_sdcard);
            return null;
        }
        try {
            filePic = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), getPhotoFileName());
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            Log.d("xxx", "saveBitmap: " + filePic.getAbsolutePath());
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        filePic.getAbsolutePath(), filePic.getName(), null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(filePic.getAbsolutePath())));
            return filePic;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("xxx", "saveBitmap: 2return");
            return null;
        }
    }

    // 使用系统当前日期加以调整作为照片的名称
    private String getPhotoFileName() {
        return System.currentTimeMillis() + ".png";
    }

    /*
     * drawable 转 bitmap
     * */
    public Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @return content Uri
     */
    public Uri getImageContentUri(Context context, String filePath) {
        File file = new File(filePath);
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (file.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

//    //uri转换为String地址
//    public String uriToRealPath(Context context, Uri uri) {
//        Cursor cursor = context.getContentResolver().query(uri,
//                new String[]{MediaStore.Images.Media.DATA},
//                null,
//                null,
//                null);
//        cursor.moveToFirst();
//        String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
//        return path;
//    }

    public static String uriToRealPath(Context context, Uri uri) {
        try {
            int sdkVersion = Build.VERSION.SDK_INT;
            if (sdkVersion >= 19) {
                //
                // return getRealPathFromUri_AboveApi19(uri);
                return getPath(context, uri);
            } else {
                return getRealFilePath(context, uri);
            }
            //return new File(new URI(uri.toString())).getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 专为Android4.4以上设计的从Uri获取文件路径
     */
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {

                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                if (id.startsWith("raw:")) {
                    final String path = id.replaceFirst("raw:", "");
                    return path;
                }
                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                };

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // 在某些android8+的手机上，无法获取路径，所以用拷贝的方式，获取新文件名，然后把文件发出去
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }

                return destinationPath;
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {

                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getRealFilePath(Context context, Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static String getFileName(@NonNull Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        String filename = null;

        if (mimeType == null && context != null) {
            filename = getName(uri.toString());
        } else {
            Cursor returnCursor = context.getContentResolver().query(uri, null,
                    null, null, null);
            if (returnCursor != null) {
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                returnCursor.moveToFirst();
                filename = returnCursor.getString(nameIndex);
                returnCursor.close();
            }
        }

        return filename;
    }

    private static String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = filename.lastIndexOf('/');
        return filename.substring(index + 1);
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    @Nullable
    private static File generateFileName(@Nullable String name, File directory) {
        if (name == null) {
            return null;
        }

        File file = new File(directory, name);

        if (file.exists()) {
            String fileName = name;
            String extension = "";
            int dotIndex = name.lastIndexOf('.');
            if (dotIndex > 0) {
                fileName = name.substring(0, dotIndex);
                extension = name.substring(dotIndex);
            }

            int index = 0;

            while (file.exists()) {
                index++;
                name = fileName + '(' + index + ')' + extension;
                file = new File(directory, name);
            }
        }

        try {
            if (!file.createNewFile()) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


        return file;
    }

    public static final String DOCUMENTS_DIR = "documents";

    private static File getDocumentCacheDir(@NonNull Context context) {
        File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return dir;
    }

    private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
        InputStream is = null;
        BufferedOutputStream bos = null;
        try {
            is = context.getContentResolver().openInputStream(uri);
            bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
            byte[] buf = new byte[1024];
            is.read(buf);
            do {
                bos.write(buf);
            } while (is.read(buf) != -1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * 将字节数组转换为ImageView可调用的Bitmap对象
     *
     * @param bytes
     * @param opts
     * @return Bitmap
     */
    public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null) {
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
            } else {
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
        return null;
    }
}